<template>
  <div>
    <el-card>
      <div class="page-title">
        <span>智能外呼</span>
      </div>

      <div style="margin-top: 20px;">
        <el-form ref="queryForm" :model="queryForm" :rules="rules" size="small">
          <el-row style="display: flex;flex-wrap: wrap;">
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item prop="taskNoOrName">
                <el-input v-model="queryForm.taskNoOrName" clearable placeholder="请输入名称，最长20字"
                          style="width: 100%;"/>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item prop="taskState">
                <el-select v-model="queryForm.taskState" clearable placeholder="请选择任务状态" style="width: 100%;">
                  <el-option v-for="item in taskStateList" :key="item.dictValue" :label="item.dictLabel"
                             :value="item.dictValue"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item prop="createTime">
                <el-date-picker v-model="queryForm.createTime"
                                :picker-options="pickerOptions"
                                end-placeholder="创建结束日期" format="yyyy-MM-dd" range-separator="至"
                                start-placeholder="创建开始日期"
                                style="width: 100%;" type="daterange" value-format="yyyy-MM-dd"
                                @change="(val) => dateChange(val, { fileBytes: ['createTime1', 'createTime2'] }, 'queryForm')"/>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item prop="repeatedlyFlag">
                <el-select v-model="queryForm.repeatedlyFlag" clearable placeholder="是否二次外呼" style="width: 100%;">
                  <el-option v-for="item in repeatedlyFlagList" :key="item.value" :label="item.label"
                             :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item prop="ocLeadName">
                <el-input v-model="queryForm.ocLeadName" clearable placeholder="请输入拓客线索名称"
                          style="width: 100%;"/>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item prop="botName">
                <el-input v-model="queryForm.botName" clearable placeholder="请输入BOT名称" style="width: 100%;"/>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item prop="startTime">
                <el-date-picker v-model="queryForm.startTime"
                                :picker-options="pickerOptions"
                                end-placeholder="执行结束日期" format="yyyy-MM-dd" range-separator="至"
                                start-placeholder="执行开始日期"
                                style="width: 100%;" type="daterange" value-format="yyyy-MM-dd"
                                @change="(val) => dateChange(val, { fileBytes: ['startTime1', 'startTime2'] }, 'queryForm')"/>
              </el-form-item>
            </el-col>
            <el-col :lg="6" :md="8" :sm="12" :xs="24" style="padding: 0;">
              <el-form-item>
                <div style="float: right;">
                  <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">查 询</el-button>
                  <el-button icon="el-icon-refresh" plain size="mini" type="info" @click="handleReset">重 置</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <el-card style="margin-top: 20px;">
      <div style="float: right;margin-bottom: 15px;">
        <!-- dialogVisible = true -->
        <el-button icon="el-icon-plus" type="primary" @click="$router.push({ path: 'intelligentOutCallDetail',query:{editFlag:'1'} })">创建任务
        </el-button>
      </div>
      <el-table v-loading="loading" :data="tableList" height="442px">
        <el-table-column align="center" label="序号" type="index" width="55"/>
        <!--  min-width="180px" show-overflow-tooltip -->
        <el-table-column align="center" label="任务名称" min-width="150px" prop="taskName" show-overflow-tooltip/>
        <el-table-column align="center" label="拓客线索" min-width="180px" prop="ocLeadName" show-overflow-tooltip/>
        <el-table-column align="center" label="外呼系统任务ID" min-width="120px" prop="outTaskId" show-overflow-tooltip/>
        <el-table-column align="center" label="BOT名称" prop="botName" min-width="160px" show-overflow-tooltip/>
        <el-table-column align="center" label="是否二次外呼" min-width="100px" prop="repeatedlyFlag" :formatter="repeatedlyFlagFormatter"/>
        <el-table-column align="center" label="外呼任务状态" min-width="100px" prop="taskState">
          <slot slot-scope="scope">
            <el-tag v-if="scope.row.taskState == '1'" class="el-tag-1">待执行</el-tag>
            <el-tag v-if="scope.row.taskState == '2'" class="el-tag-2">执行中</el-tag>
            <el-tag v-if="scope.row.taskState == '3'" class="el-tag-3">已暂停</el-tag>
            <el-tag v-if="scope.row.taskState == '4'" class="el-tag-4">已终止</el-tag>
            <el-tag v-if="scope.row.taskState == '5'" class="el-tag-5">已完成</el-tag>
            <el-tag v-if="['1','2','3','4','5'].indexOf(scope.row.taskState) == -1" class="el-tag-6">状态异常</el-tag>
          </slot>
        </el-table-column>
        <el-table-column align="center" label="任务执行时间" min-width="160px" prop="startTime"/>
        <el-table-column align="center" label="外呼并发数量" min-width="100px" prop="robotCount"/>
        <el-table-column align="center" label="导入数量" prop="inputCount"/>
        <el-table-column align="center" label="外呼数量" prop="reqCount"/>
        <el-table-column align="center" label="接听率" prop="answeredRate"/>
        <el-table-column align="center" label="挂机率" prop="customerHangupPercent"/>
        <el-table-column align="center" label="A类客户数" min-width="90px" prop="customerConcernA"/>
        <el-table-column align="center" label="B类客户数" min-width="90px" prop="customerConcernB"/>
        <el-table-column align="center" label="创建人" min-width="100px" prop="createdBy"/>
        <el-table-column align="center" label="任务创建时间" min-width="160px" prop="createdTime"/>
        <!--  min-width="130px" -->
        <el-table-column align="center" fixed="right" label="操作" min-width="330px" prop="">
          <template slot-scope="{ row }">
            <el-button v-if="['3'].indexOf(row.taskState) > -1" size="mini" type="text" @click="startTask(row.taskNo)" v-has-permi="['admin:ioctask:edit']">开始任务</el-button>
            <el-button v-if="['1'].indexOf(row.taskState) > -1" size="mini" type="text" @click="$router.push({path: 'intelligentOutCallDetail', query: {id: row.taskNo, editFlag: '2'}})" v-has-permi="['admin:ioctask:edit']">编辑</el-button>
            <el-button v-if="['1','2','3','4','5'].indexOf(row.taskState) > -1" size="mini" type="text"
                       @click="$router.push({ path: 'detailedTasks', query: { id: row.taskNo, taskName: row.taskName, taskState: row.taskState, flag: '1' } })" v-has-permi="['admin:ioctask:query']">任务明细
            </el-button>
            <el-button v-if="['2','3','4','5'].indexOf(row.taskState) > -1" size="mini" type="text" @click="$router.push({path: 'intelligentOutCallDetail', query: {id: row.taskNo, editFlag: '3'}})" v-has-permi="['admin:ioctask:query']">详情</el-button>
            <el-button v-if="['2'].indexOf(row.taskState) > -1" size="mini" type="text" @click="pauseTask(row.taskNo)" v-has-permi="['admin:ioctask:edit']">暂停任务</el-button>
            <el-button v-if="['2','3'].indexOf(row.taskState) > -1" size="mini" type="text" @click="terminateTask(row.taskNo)" v-has-permi="['admin:ioctask:edit']">停止任务</el-button>
            <el-button v-if="['5'].indexOf(row.taskState) > -1 && row.repeatedlyFlag == '1'" size="mini"
                       type="text" @click="$router.push({ path: 'detailedTasks', query: {id: row.taskNo, taskName: row.taskName, taskState: row.taskState, flag: '2' } })" v-has-permi="['admin:ioctask:query']">二次外呼明细
            </el-button>
            <el-button v-if="['1'].indexOf(row.taskState) > -1" size="mini" type="text" @click="deleteTask(row.taskNo)" v-has-permi="['admin:ioctask:edit']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total"
                        @handleCurrentChange="handleCurrentChange"
                        @handleSizeChange="handleSizeChange"></NormalPagination>
    </el-card>

    <el-dialog :title="dialogObj.title" :visible.sync="dialogVisible" top="15% !important" width="300px">
      <div style="text-align: center;height: 50px;line-height: 50px;">
        <i class="el-icon-question" style="color: #082aff;margin-right: 10px;"></i><span>{{ dialogObj.content }}</span>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false" :loading="dialoading">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitTask" :loading="dialoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import {queryIocTaskList, startTask, pauseTask, terminateTask, deleteTask} from "@/api/intelligentOutCall";

export default {
  name: "IntelligentOutCall",
  data() {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const start = new Date();
            picker.$emit('pick', [start, start]);
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
            picker.$emit('pick', [start, start]);
          }
        }, {
          text: '过去7天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '过去30天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '本周',
          onClick(picker) {
            picker.$emit('pick', [new Date(moment().weekday(0)), new Date(moment().weekday(6))]);
          }
        }, {
          text: '上周',
          onClick(picker) {
            picker.$emit('pick', [new Date(moment().week(moment().week() - 1).startOf('week')), new Date(moment().week(moment().week() - 1).endOf('week'))]);
          }
        }, {
          text: '本月',
          onClick(picker) {
            picker.$emit('pick', [new Date(moment().startOf('month')), new Date(moment().endOf('month'))]);
          }
        }, {
          text: '上月',
          onClick(picker) {
            picker.$emit('pick', [new Date(moment().month(moment().month() - 1).startOf('month')), new Date(moment().month(moment().month() - 1).endOf('month'))]);
          }
        }]
      },
      loading: false,
      dialogVisible: false,
      dialogObj: {
        title: '开始确认',
        content: '确认开始该任务吗？',
        icon: 'question',
        fn: ''
      },
      queryForm: {
        pageNum: 1,
        pageSize: 20,
        createTime: [],
        startTime: [],
        ocLeadName: '',
        taskNoOrName: '',
        botName: '',
        taskState: '',
        createTime1: '',
        createTime2: '',
        startTime1: '',
        startTime2: '',
      },
      rules: {
        taskNoOrName: [{required: false, max: 20, message: '名称输入有误，请重新输入', trigger: 'blur'}]
      },
      total: 0,
      taskStateList: [],
      repeatedlyFlagList: [
        {value: '1', label: '是'},
        {value: '0', label: '否'},
      ],
      tableList: [],
      nowTaskNo: '',
      nowTaskFlag: '',
      dialoading: false,
    }
  },
  methods: {
    // 是否二次外呼格式化
    repeatedlyFlagFormatter(row, column){
      return row.repeatedlyFlag == '1' ? '是':'否'
    },
    getListFn() {
      let obj = {
        ...this.queryForm
      }
      this.loading = true
      this.$refs.queryForm.validate(valid => {
        if(valid){
          queryIocTaskList(obj).then(res => {
            console.log(res, 'res')
            this.tableList = res.rows
            this.total = res.total
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }else{
          this.$message.error('查询条件有误，请核实')
          this.loading = false
        }
      })
    },
    handleQuery() {
      this.queryForm.pageNum = 1
      this.getListFn()
    },
    handleReset() {
      this.queryForm = {
        pageNum: 1,
        pageSize: 20,
        createTime: null,
        startTime: null,
        ocLeadName: '',
        taskNoOrName: '',
        botName: '',
        taskState: '',
        createTime1: '',
        createTime2: '',
        startTime1: '',
        startTime2: '',
      }
      this.handleQuery()
    },
    // 翻页
    handleSizeChange(value) {
      this.queryForm.pageNum = 1
      this.queryForm.pageSize = value
      this.getListFn()
    },
    handleCurrentChange(value) {
      this.queryForm.pageNum = value
      this.getListFn()
    },
    // range 日期change事件
    dateChange(val, item, byte) {
      let valNew = val || ["", ""];
      item.fileBytes.forEach((fileByte, index) => this.$set(this[byte], fileByte, valNew[index]));
    },
    startTask(val){
      this.dialogVisible = true
      this.nowTaskNo = val
      this.nowTaskFlag = 'start'
      this.dialogObj = {
        title: '开始确认',
          content: '确认开始该任务吗？',
          icon: 'question',
          fn: ''
      }
    },
    pauseTask(val){
      this.dialogVisible = true
      this.nowTaskNo = val
      this.nowTaskFlag = 'pause'
      this.dialogObj = {
        title: '暂停确认',
        content: '确认暂停该任务吗？',
        icon: 'question',
        fn: ''
      }
    },
    terminateTask(val){
      this.dialogVisible = true
      this.nowTaskNo = val
      this.nowTaskFlag = 'terminate'
      this.dialogObj = {
        title: '终止确认',
        content: '确认终止该任务吗？',
        icon: 'question',
        fn: ''
      }
    },
    deleteTask(val){
      this.dialogVisible = true
      this.nowTaskNo = val
      this.nowTaskFlag = 'delete'
      this.dialogObj = {
        title: '删除确认',
        content: '确认删除该任务吗？',
        icon: 'question',
        fn: ''
      }
    },
    submitTask(){
      this.dialoading = true
      if(this.nowTaskFlag == 'start'){
        startTask({taskNo: this.nowTaskNo}).then(res => {
          this.$message.success('任务开始成功')
          this.dialogVisible = false
          this.getListFn()
          this.dialoading = false
        }).catch(() => {
          this.dialoading = false
        })
      }else if(this.nowTaskFlag == 'pause'){
        pauseTask({taskNo: this.nowTaskNo}).then(res => {
          this.$message.success('任务暂停成功')
          this.getListFn()
          this.dialogVisible = false
          this.dialoading = false
        }).catch(() => {
          this.dialoading = false
        })
      }else if(this.nowTaskFlag == 'terminate'){
        terminateTask({taskNo: this.nowTaskNo}).then(res => {
          this.$message.success('任务终止成功')
          this.dialogVisible = false
          this.getListFn()
          this.dialoading = false
        }).catch(() => {
          this.dialoading = false
        })
      }else if(this.nowTaskFlag == 'delete'){
        deleteTask({taskNo: this.nowTaskNo}).then(res => {
          this.$message.success('任务删除成功')
          this.dialogVisible = false
          this.getListFn()
          this.dialoading = false
        }).catch(() => {
          this.dialoading = false
        })
      }
    },
  },
  mounted() {
    this.getDicts('ioc_task_state').then(res => {
      this.taskStateList = res.data
    })
    this.handleQuery()
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

.page-title {
  font-size: 20px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #2A2A2A;
  margin-top: 10px;
  margin-left: 10px;
}

.my-normal-form-bg {
  // padding: 16px;
  border: 0;
  overflow: visible;

  .page-title {
    font-size: 20px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #2A2A2A;
    margin-top: 10px;
    margin-left: 10px;
  }

  .operate-form {
    position: relative;

    .btn {
      position: absolute;
      bottom: 0px;
      right: 10px;

      .el-button {
        margin: 0 0 10px 16px;
      }
    }
  }

  // ::v-deep.el-card__body {
  //   padding: 10px 20px 0 20px;
  // }

  // ::v-deep.el-card__header {
  //   padding: 8px 0 0 0;
  //   border: 0;
  // }
}

::v-deep.el-tag-1 {
  background: rgba(255, 173, 58, 0.1) !important;
  border-radius: 3px !important;
  border: 1px solid #FFAD3A !important;
  color: #FFAD3A !important;
}

::v-deep.el-tag-2 {
  background: rgba(252, 88, 48, 0.1) !important;
  border-radius: 3px !important;
  border: 1px solid #082aff !important;
  color: #082aff !important;
}

::v-deep.el-tag-3 {
  background: rgba(153, 153, 153, 0.1) !important;
  border-radius: 3px !important;
  border: 1px solid rgba(204, 204, 204, 0.2) !important;
  color: #999999 !important;
}

::v-deep.el-tag-4 {
  background: rgba(242, 48, 49, 0.1) !important;
  border-radius: 3px !important;
  border: 1px solid rgba(242, 48, 49, 0.1) !important;
  color: #F23031 !important;
}

::v-deep.el-tag-5 {
  background: rgba(20, 213, 149, 0.1) !important;
  border-radius: 3px !important;
  border: 1px solid rgba(20, 213, 149, 0.1) !important;
  color: #14D595 !important;
}

::v-deep.el-tag-6 {
  background: rgba(153, 153, 153, 0.2) !important;
  border-radius: 3px !important;
  border: 1px solid rgba(204, 204, 204, 0.2) !important;
  color: #999999 !important;
}
</style>
